// src/api/request.ts
const API_BASE_URL = '/api/v1'

// 通用请求函数
export async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
  const fullUrl = url.startsWith('/api/') ? url : `${API_BASE_URL}${url.startsWith('/') ? url : `/${url}`}`
  
  const defaultOptions: RequestInit = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers
    },
    ...options
  }

  try {
    const response = await fetch(fullUrl, defaultOptions)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    return data
  } catch (error) {
    console.error('API请求失败:', error)
    throw error
  }
}

// GET请求
export async function get<T>(url: string): Promise<T> {
  return request<T>(url, { method: 'GET' })
}

// POST请求
export async function post<T>(url: string, data?: any): Promise<T> {
  return request<T>(url, {
    method: 'POST',
    body: JSON.stringify(data)
  })
}

// PUT请求
export async function put<T>(url: string, data?: any): Promise<T> {
  return request<T>(url, {
    method: 'PUT',
    body: JSON.stringify(data)
  })
}

// DELETE请求
export async function del<T>(url: string): Promise<T> {
  return request<T>(url, { method: 'DELETE' })
}